package cn.lijiajia3515.cairo.captcha.image;

import cn.lijiajia3515.cairo.captcha.CaptchaArgs;
import cn.lijiajia3515.cairo.captcha.CaptchaHandler;
import cn.lijiajia3515.cairo.captcha.image.graph.DelegatingGraphImageHandler;
import cn.lijiajia3515.cairo.captcha.image.graph.GraphImageArgs;
import cn.lijiajia3515.cairo.captcha.image.graph.GraphImageHandler;
import lombok.Setter;
import reactor.util.function.Tuple2;

/**
 * 图形验证码 行为控制
 */
public abstract class ImageCaptchaHandler implements CaptchaHandler {
	@Setter
	protected GraphImageHandler graphImageHandler = new DelegatingGraphImageHandler();

	public ImageCaptchaHandler() {

	}

	public ImageCaptchaHandler(GraphImageHandler handler) {
		this.graphImageHandler = handler;
	}


	@Override
	public ImageCaptcha getCaptcha(CaptchaArgs args) {
		if (!(args instanceof ImageCaptchaArgs)) throw new RuntimeException("无法生成图形验证码");
		ImageCaptchaArgs imageCaptchaArgs = (ImageCaptchaArgs) args;
		Tuple2<String, String> str = getImageCaptchaStr(args);
		ImageCaptcha.ImageCaptchaDetail detail = graphImageHandler.getDetail(
			GraphImageArgs.builder()
				.width(imageCaptchaArgs.getWidth())
				.height(imageCaptchaArgs.getHeight())
				.imageStr(str.getT2())
				.build()
		);
		return ImageCaptcha.builder()
			.code(str.getT1())
			.detail(detail)
			.build();
	}

	/**
	 * @param args 参数
	 * @return 验证码
	 */
	protected abstract Tuple2<String, String> getImageCaptchaStr(CaptchaArgs args);


}
